<template>
    <div>
        <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="selectHandle" />
        <van-empty v-if="list.length === 0" description="请先完善收获地址" />
    </div>
</template>

<script>
import { fetchGetUserAddress } from "../api/address.js"
export default {
    data() {
        return {
            chosenAddressId: "", // 默认地址ID
            list: [],
        };
    },
    created() {
        this._fetchUserAddress();
    },
    methods: {
        onAdd() {
            this.$router.push('/addAddress')
        },
        onEdit(item, index) {
            this.$toast("编辑地址:" + index);
            this.$router.push('/editaddress/' + JSON.stringify(this.list[index]))
        },
        async _fetchUserAddress() {
            let userid = this.$store.state.userInfo.id
            let addressAll = await fetchGetUserAddress(userid);
            // console.log(222)
            if (addressAll.length === 0) {
                return;
            }
            // 把默认地址排在第一位
            addressAll = addressAll.map(item => {
                // 额外设置一个属性，保存省市区的编码
                item.fullAreaCode = item.areaCode;
                item.areaCode = item.areaCode.split('-')[2]
                if (item.isDefault) {
                    // 显示默认文字
                    item.isDefault = true
                } else {
                    item.isDefault = false
                }
                return item;
            })
            let index = addressAll.findIndex(item => item.isDefault == true)
            // 若有默认地址。则把默认排在第一位
            if (index !== -1) {
                let defaultAddress = addressAll[index]
                // 设置地址勾选
                this.chosenAddressId = defaultAddress.id
                addressAll.splice(index, 1) // 删除
                addressAll.unshift(defaultAddress) // 添加到头部
            } else {
                this.chosenAddressId = addressAll[0].id
            }

            this.list = addressAll;
        },
        // 切换选中的地址
        selectHandle(addressInfo, index) {
            // 把当前选中的地址存入到本地存储
            localStorage.setItem('harvestAddress', JSON.stringify(addressInfo))
            //返回是一页面
            // this.$router.back();
        }
    }
};
</script>

<style lang="scss" scoped>
</style>
